import 'package:aqua_plunge/media/video_play_item_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controller/DatabaseListController.dart';
import '../model/media.dart';

class MediaPage extends StatefulWidget {
  final int currentPageIndex;

  const MediaPage({super.key, required this.currentPageIndex});

  @override
  State<MediaPage> createState() => _PageViewState();
}

class _PageViewState extends State<MediaPage>
    with AutomaticKeepAliveClientMixin {
  int _currentVideoIndex = 0;
  late PageController _pageController;
  final DatabaseController _databaseController = Get.find<DatabaseController>();

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentVideoIndex);
  }

  void _pauseVideo() {
    if (_currentVideoIndex < _databaseController.videoControllers.length) {
      _databaseController.videoControllers[_currentVideoIndex].pause();
    }
  }

  void _playVideo() {
    if (_currentVideoIndex < _databaseController.videoControllers.length &&
    _databaseController.videoControllers[_currentVideoIndex].value.isInitialized
    ) {
          _databaseController.videoControllers[_currentVideoIndex].play();
    }
  }

  @override
  void didUpdateWidget(covariant MediaPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentPageIndex != 1) {
      _pauseVideo();
    } else {
      _playVideo();
    }
  }

  Widget _buildVideoPageView() {
    return Obx(() {
      return PageView.builder(
        onPageChanged: (index) {
          setState(() {
            _pauseVideo();
            _currentVideoIndex = index;
            if(!_databaseController.videoControllers[index].value.isPlaying){
              _databaseController.videoControllers[index].play();
            }
            _databaseController.setVideoIndex(_currentVideoIndex);
          });
        },
        controller: _pageController,
        itemCount: _databaseController.mediaList.length,
        scrollDirection: Axis.vertical,
        itemBuilder: (context, index) {
          Media media = _databaseController.mediaList[index];
          return VideoPlayItemPage(
            media: media,
            onBlock: _blockItem,
            videoPlayerController: _databaseController.videoControllers[index],
            pageIndex: widget.currentPageIndex,
          );
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: _buildVideoPageView(),
    );
  }

  @override
  void dispose() {
    for (var controller in _databaseController.videoControllers) {
      controller.dispose();
    }
    _pageController.dispose();
    super.dispose();
  }

  void _blockItem() {
    setState(() {
      _pauseVideo();
      _databaseController.fetchCreationData();
      _databaseController.fetchMediaData();
      _pageController.animateToPage(_currentVideoIndex, duration: const Duration(milliseconds: 100), curve: Curves.easeIn);
    });
  }

  @override
  bool get wantKeepAlive => true;
}
